package com.cskaoyan.utils;


import com.cskaoyan.exception.ParamsException;
import com.cskaoyan.model.BaseRespVo;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.util.List;
import java.util.Objects;

/**
 * @author 如果有字段错误，或者全局的错误，也即是对整个类的几个联合字段的验证有错误。需要自定义注解
 * @date 2022/01/03 17:48
 */
public class ValidationUtil {

    public static void validate(BindingResult bindingResult) throws ParamsException {

        if (bindingResult.hasFieldErrors()) {
            final FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                final String field = fieldError.getField();
                final String defaultMessage = fieldError.getDefaultMessage();
                throw new ParamsException("field error in " + field + ",reason for:" + defaultMessage);
            }
        } else if (bindingResult.hasGlobalErrors()) {
            ObjectError globalError = bindingResult.getGlobalError();
            if (globalError != null) {
                throw new ParamsException(globalError.getDefaultMessage());
            }
            throw new ParamsException("参数错误");
        }

    }
}
